<template>
    <div class="user-container">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>角色列表</span>
            <el-button type="primary" @click="handleAdd">新增角色</el-button>
          </div>
        </template>
        <el-table :data="roleData" style="width: 100%" v-loading="loading"> 
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="roleName" label="角色名" />
          <el-table-column prop="roleCode" label="角色编码" />
          <el-table-column prop="description" label="角色描述" />
          <el-table-column prop="gmtCreate" label="创建时间" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 添加/编辑角色对话框 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="500px"
        @close="resetForm"
      >
        <el-form
          ref="roleFormRef"
          :model="roleForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色编码" prop="roleCode">
            <el-input v-model="roleForm.roleCode" placeholder="请输入角色编码" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input
              v-model="roleForm.description"
              type="textarea"
              placeholder="请输入角色描述"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm" :loading="submitLoading">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
</template>
  
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios';

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const submitLoading = ref(false)
const roleData = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const roleFormRef = ref(null)

// 表单数据
const roleForm = reactive({
  id: '',
  roleName: '',
  roleCode: '',
  description: ''
})

// 表单验证规则
const rules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  roleCode: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[a-zA-Z_]+$/, message: '角色编码只能包含字母和下划线', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ]
}

const getRoleList = () => {
  loading.value = true
  axios({
    url: '/api/sysrole/sysRole/showAll',
    method: 'get'
  }).then((res) => {
    if (res.data.code === 200) {
      roleData.value = res.data.data
    } else {
      ElMessage.error(res.data.msg || '获取角色列表失败')
    }
  }).catch((error) => {
    ElMessage.error('获取角色列表失败')
    console.error(error)
  }).finally(() => {
    loading.value = false
  })
}

// 重置表单
const resetForm = () => {
  if (roleFormRef.value) {
    roleFormRef.value.resetFields()
  }
  Object.assign(roleForm, {
    id: '',
    roleName: '',
    roleCode: '',
    description: ''
  })
}

// 新增角色
const handleAdd = () => {
  dialogTitle.value = '新增角色'
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row) => {
  dialogTitle.value = '编辑角色'
  Object.assign(roleForm, row)
  dialogVisible.value = true
}

// 删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除角色"${row.roleName}"吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    axios({
      url: `/api/sysrole/sysRole/deleteById/${row.id}`,
      method: 'delete'
    }).then((res) => {
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        getRoleList()
      } else {
        ElMessage.error(res.data.msg || '删除失败')
      }
    }).catch((error) => {
      ElMessage.error('删除失败')
      console.error(error)
    })
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  if (!roleFormRef.value) return
  
  roleFormRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      const isEdit = !!roleForm.id
      const url = isEdit 
        ? `/api/sysrole/sysRole/update/${roleForm.id}`
        : '/api/sysrole/sysRole/add'
      const method = isEdit ? 'put' : 'post'

      axios({
        url,
        method,
        data: roleForm
      }).then((res) => {
        if (res.data.code === 200) {
          ElMessage.success(isEdit ? '修改成功' : '添加成功')
          dialogVisible.value = false
          getRoleList()
        } else {
          ElMessage.error(res.data.msg || (isEdit ? '修改失败' : '添加失败'))
        }
      }).catch((error) => {
        ElMessage.error(isEdit ? '修改失败' : '添加失败')
        console.error(error)
      }).finally(() => {
        submitLoading.value = false
      })
    }
  })
}

onMounted(() => {
  getRoleList()
})
</script>
  
<style lang="scss" scoped>
.user-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 